package com.example.voltorb.flip;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;

import com.example.voltorb.flip.Game.GameState;

public class MainActivity extends Activity {
	
	private Game game;
	private Dialog dialog;
	private GridView gridView;
	private FrameLayout overlay;
	
	private SharedPreferences sharedPref;

	private static final int DEFAULT_GRID_ROWS = 5;
	private static final int DEFAULT_GRID_COLUMNS = 5;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        this.dialog = null;
        
        // Get preferences
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        
        initNewGame();
        
		this.overlay = (FrameLayout) findViewById(R.id.overlay);
		this.overlay.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				initNewGameBoard();
				v.setVisibility(View.GONE); 
			}
		});
		this.overlay.bringToFront();
		this.overlay.setVisibility(View.GONE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			startActivity(new Intent(this.getApplicationContext(), SettingsActivity.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public Game getGame() {
		return this.game;
	}

	private void initNewGame() {
        this.game = new Game(this,
        		Integer.parseInt(sharedPref.getString("pref_rows", "" + DEFAULT_GRID_ROWS)),
        		Integer.parseInt(sharedPref.getString("pref_cols", "" + DEFAULT_GRID_COLUMNS)));
        this.updateDescription();
        this.updateCollectedCoins();
        
        // Get hold of the board grid in the layout
        this.gridView = (GridView) findViewById(R.id.boardGrid);
        
        // Assign an adapter created with the created tiles from the game instance
        this.gridView.setAdapter(new TileAdapter(this.getApplicationContext(), game.getTiles()));
        
        // Specify what happens when clicking the board grid
        this.gridView.setOnItemClickListener(new OnTileClickListener(this));
        
        // Set properties for the adapter
        this.gridView.setNumColumns(this.game.gridColumns + 1);
        this.gridView.setHorizontalSpacing(4);
        this.gridView.setVerticalSpacing(4);
//        gv.setPadding(4, 4, 4, 4);
	}
	
	private void initNewGameBoard() {
		this.game.initNewBoard();
        this.updateDescription();
        this.updateCurrentCoins();
        this.updateCollectedCoins();
		((TileAdapter) this.gridView.getAdapter()).notifyDataSetChanged();
	}

	public void showEndingDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		if (this.game.getState() == GameState.WON) {
			// Build dialog
			builder.setMessage("You won!")
			.setTitle("Game cleared");
		} else {
			// Build dialog
			builder.setMessage("You lost!")
			.setTitle("Game over");
		}
		// Create the dialog
		this.dialog = builder.create();
		this.dialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface arg0) {
				showBoard();
			}
		});
		dialog.setCanceledOnTouchOutside(true);
		// Show the damn dialog!
		dialog.show();
	}

	private void showBoard() {
		this.game.showBoard();
		((TileAdapter) this.gridView.getAdapter()).notifyDataSetChanged();
		this.overlay.setVisibility(View.VISIBLE);
	}

	private void updateDescription() {
		TextView tv = (TextView) findViewById(R.id.description_label);
		String description = getResources().getString(R.string.description);
		tv.setText(String.format(description, this.game.getLevel()));
	}

	public void updateCurrentCoins() {
		TextView tv = (TextView) findViewById(R.id.current_coins);
		tv.setText(String.format("%05d", this.game.getCollectedCoins()));
	}

	public void addCollectedCoins() {
        int totalCoins = sharedPref.getInt("collected_coins", 0);
		SharedPreferences.Editor e = this.sharedPref.edit();
		e.putInt("collected_coins", totalCoins + this.game.getCollectedCoins());
		e.commit();
	}
	
	private void updateCollectedCoins() {
		TextView tv = (TextView) findViewById(R.id.collected_coins);
        int totalCoins = sharedPref.getInt("collected_coins", 0);
		tv.setText(String.format("%05d", totalCoins));
	}
	
	public boolean toggleMarkMode(View v) {
		return this.game.toggleMarkMode();
	}
}
